import logging
import os
from logging.handlers import TimedRotatingFileHandler
from datetime import datetime
from app.config.settings import settings
import contextvars

# 使用contextvars存储request_id，这在异步环境中是安全的
request_id_context: contextvars.ContextVar[str] = contextvars.ContextVar('request_id', default='N/A')

class RequestIdFilter(logging.Filter):
    """
    日志过滤器，用于添加request_id到日志记录中
    """
    def filter(self, record):
        # 从contextvars获取request_id
        request_id = request_id_context.get()
        record.request_id = request_id
        return True


def set_request_id(request_id: str):
    """
    设置当前上下文的request_id
    """
    request_id_context.set(request_id)


def get_request_id() -> str:
    """
    获取当前上下文的request_id
    """
    return request_id_context.get()


def setup_logger(name: str = None):
    """
    设置日志记录器，支持控制台和文件输出，按天滚动
    
    Args:
        name: 日志记录器名称，默认从settings中获取
        
    Returns:
        logging.Logger: 配置好的日志记录器
    """
    logger_name = name or settings.LOGGER_NAME
    
    # 创建logger
    logger = logging.getLogger(logger_name)
    logger.setLevel(logging.DEBUG)
    
    # 避免重复添加handler
    if logger.handlers:
        return logger
    
    # 创建格式化器
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - [Request-ID: %(request_id)s] - %(message)s'
    )
    
    # 创建request_id过滤器
    request_id_filter = RequestIdFilter()
    
    # 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(formatter)
    console_handler.addFilter(request_id_filter)
    logger.addHandler(console_handler)
    
    # 文件处理器 - 按天滚动，用于常规日志
    log_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "logs")
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
        
    log_file = os.path.join(log_dir, f"{logger_name}.log")
    file_handler = TimedRotatingFileHandler(
        log_file,
        when="midnight",
        interval=1,
        backupCount=30,  # 保留30天的日志
        encoding="utf-8"
    )
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(formatter)
    file_handler.addFilter(request_id_filter)
    logger.addHandler(file_handler)
    
    # 错误日志文件处理器 - 专门记录错误及以上级别的日志
    error_log_file = os.path.join(log_dir, f"{logger_name}_error.log")
    error_file_handler = TimedRotatingFileHandler(
        error_log_file,
        when="midnight",
        interval=1,
        backupCount=90,  # 保留90天的错误日志
        encoding="utf-8"
    )
    error_file_handler.setLevel(logging.ERROR)
    error_file_handler.setFormatter(formatter)
    error_file_handler.addFilter(request_id_filter)
    logger.addHandler(error_file_handler)
    
    # 添加过滤器到logger
    logger.addFilter(request_id_filter)
    
    return logger


# 创建全局logger实例
logger = setup_logger()